package com.sskj.utils;

import org.apache.commons.lang.StringUtils;

public class CodingUtil {

	public static String getMaxIDQuery(String maxCode, String cdlike, Integer cdlen) throws Exception {

		long maxId = 0;

		String[] saLike = null;
		if (!StringUtils.isEmpty(cdlike)) {
			if (!cdlike.contains("%")) {
				cdlike = cdlike + "%";
			}
			saLike = cdlike.split("%");
			if (saLike.length > 2) {
				throw new Exception("编码【" + cdlike + "】Like字符串错误！");
			}
		} else {
			throw new Exception("编码Like字符串为空！");
		}

		if (maxCode != null) {
			try {
				String tmpNumber = "";
				if (!StringUtils.isEmpty(cdlike)) {
					String[] sasLike = cdlike.split("%");
					if (sasLike.length == 1) {
						tmpNumber = maxCode.substring(sasLike[0].length(), maxCode.length());
					} else if (sasLike.length == 2) {
						tmpNumber = maxCode.substring(sasLike[0].length(), maxCode.length() - sasLike[1].length());
					} else {
						throw new Exception("编码【" + cdlike + "】Like字符串错误！");
					}

				} else {
					tmpNumber = maxCode;
				}
				maxId = new Long(tmpNumber).longValue();
			} catch (Exception e) {
				e.printStackTrace();
				throw new Exception("编码错误！");
			}
		}

		maxId++;
		String temp = String.valueOf(maxId);
		if (!StringUtils.isEmpty(cdlike)) {

			if (saLike.length == 1) {
				return saLike[0] + "00000000000000".substring(0, cdlen - saLike[0].length() - temp.length()) + temp;
			} else if (saLike.length == 2) {
				return saLike[0]
						+ "00000000000000".substring(0, cdlen - saLike[0].length() - saLike[1].length() - temp.length())
						+ temp + saLike[1];
			}
		}
		throw new Exception("编码错误！");
	}
}
